/*
 * Copyright 2010 Michael Nitsche
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package de.mnit.basis.daten;

import de.mnit.basis.fehler.Fehler;



/**
 * @author Michael Nitsche
 * Erstellt: 23.02.2008
 */
public class WandleZahl {

	/**
	 * Umgekehrt einfach mit (byte)
	 */
	public static int zuInt(byte b) {
		return b&255;
	}

	public static String zuString(Integer integer) {
		if(integer==null)
			return null;
		return ""+integer;
	}



	private static final String hex_zeichen ="0123456789ABCDEF";
	private static final char[] hex_zeichen_ca =hex_zeichen.toCharArray();


	public static String zuHex(byte[] ba) {
		StringBuilder sb=new StringBuilder();
		int i;
		for(byte b : ba) {
//			high = ((int)ba[i] & 0x000000FF) / 16;
//			low  = ((int)ba[i] & 0x000000FF) % 16;
			i    = b & 0xFF; // macht aus den negativen Bytezahlen richtige Integer-Pluszahlen
			sb.append(hex_zeichen_ca[i / 16]);
			sb.append(hex_zeichen_ca[i % 16]);
		}
		return sb.toString();
	}

	public static byte[] vonHex(String s) {
		Fehler.zahl.wenn_Nicht(0, s.length() % 2);
		byte[] erg=new byte[s.length()/2];
		Integer puffer=null;

		byte[] ba=s.toUpperCase().getBytes();
		int pos=0;
		for(byte b : ba) {
			if(puffer==null) //high
				puffer=hex_zeichen.indexOf(b)*16;
			else { //low
				erg[pos]=(byte)(puffer+hex_zeichen.indexOf(b));
				puffer=null;
				pos++;
			}
		}
		return erg;
	}

}
